package test.pcs;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created on 2017/4/27.
 */
public class ConcurrentUtil {
    private static final int nThread = 20;

    public static <T, V> List<T> getTargetList(final List<V> args, final Object service,
                                               final String methodName, final Class argClasses) {
        List<T> targetList = new ArrayList<T>();
        if (CollectionUtils.isEmpty(args) || service == null || methodName == null) {
            return targetList;
        }
        try {
            final Method method = service.getClass().getDeclaredMethod(methodName, argClasses);
            method.setAccessible(true);

            ExecutorService pool = Executors.newFixedThreadPool(Math.min(args.size(), nThread));
            List<Future<T>> futures = new ArrayList<Future<T>>();
            for (final V arg : args) {
                Future<T> future = pool.submit(new Callable<T>() {
                    @Override
                    public T call() throws Exception {
                        Object o = null;
                        try {
                            o = method.invoke(service, arg);
                        } catch (Exception e) {
                            throw new RuntimeException("--", e);
                        }
                        return (T) o;
                    }
                });
                futures.add(future);
            }
            pool.shutdown();
            for (Future<T> future : futures) {
                T target = null;
                try {
                    target = future.get();
                } catch (Exception e) {
                    throw new RuntimeException("--", e);
                }
                if (target != null) {
                    targetList.add(target);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("--", e);
        }
        return targetList;
    }
}
